package ass.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ass.beans.UserBean;
import ass.dao.support.UserDAOImpl;
import ass.util.Mail;

import javax.mail.*;
import javax.mail.internet.*;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");
		String password2 = (String) request.getParameter("password2");
		String email = (String) request.getParameter("email");
		
		if (password.equals(password2)) {
			UserBean userBean = new UserBean();
			userBean.setUsername(username);
			userBean.setPassword(password);
			userBean.setEmail(email);

			UUID randomString = UUID.randomUUID();
			
			userBean.setVerify_code(randomString.toString());
			userBean.setActive("N");
			
			UserDAOImpl userDAOImpl = new UserDAOImpl();
			userDAOImpl.insert(userBean);
			
			response.setContentType("text/html");// from response, set content type
			PrintWriter out = response.getWriter();// from response, get output writer
			out.write("insert succesful");
			
			String nextJSP = "";
			nextJSP = "/index.jsp";
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
			
			String[] recipients = new String[1];
			recipients[0] = email;
			
			
			try {
				Mail.postMail(recipients, "test", "confirmation code = <a href='http://localhost:8080/ass3COMP9321V2/Verify?id=" + randomString.toString() +"&username="+username+"'> </a>" , "matrixapplication@gmail.com");
			} catch (MessagingException e) {
				e.printStackTrace();
			}
			request.setAttribute("email_confirm", "<font color='red'>Please confirm your email by clicking the confirmation url in your email</font>");
			dispatcher.forward(request, response);
			
			out.close();
		}
		
	}

}
